﻿using System.Windows;
using System.Windows.Media;

namespace TotalApplication.services
{
    public static class TreeHelper
    {
        /// <summary>
        /// 在可视化树中查找指定类型的父控件
        /// </summary>
        /// <typeparam name="T">目标父控件的类型(例如 ItemsControl)</typeparam>
        /// <param name="child">起始子控件</param>
        /// <returns>找到的父控件，若未找到则返回 null</returns>
        public static T? FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);
            if (parentObject == null) 
                return null;
            if(parentObject is T parent)
            {
                return parent;
            }
            else
            {
                // 递归向上查找
                return FindVisualParent<T>(parentObject);
            }
        }
    }
}
